var express = require('express');
var router = express.Router();


const Query = require('../utils/db.js')

const md5 = require('md5')
const { v4: uuidv4 } = require('uuid')

const { getToken, md5Screat } = require('../utils/config')

// let md5Screat = '我是一个锁子asdfg'



/* GET home page. */
router.get('/', async function (req, res, next) {
  res.send('登录注册');
});



//注册
router.post('/register', async function (req, res, next) {
  let { username = '', password = '', repwd = '' } = req.body


  if (username == '' || password == '' || repwd == '') {
    next({
      msg: '请传递必要参数',
      status: 500
    })
    return
  }

  if (password != repwd) {
    next({
      msg: '请保持密码一致',
      status: 500
    })
    return
  }

  //添加sql语句
  // let sql2 = `SELECT * FROM e_member WHERE username = '${username}'`
  // let res2 = await Query(sql2)
  // if (res2.result.length > 0) {
  //   next({
  //     msg: '用户已经注册',
  //     status: 200
  //   })
  //   return
  // }

  password =md5(password+md5Screat)
  // res.send(password)
  // return
  let createdate = Date.now();
  let mid = uuidv4()

  let sql = `INSERT INTO e_member ( mid,username,password,createdate)VALUES('${mid}','${username}','${password}','${createdate}')`


  let res1 = await Query(sql)

  
 
  if (res1.result.affectedRows > 0) {
    let data = {
      msg: 'ok',
      status: 200
    }
    res.send(data);
  }
});



//登录
router.post('/login', async function (req, res, next) {
  let { username = '', password = '' } = req.body

  // res.send(password)
  // return
  if (!username || !password) {
    next({
      msg: '请传递必要参数'
    })
    return
  }

  password = md5(password + md5Screat)
  // res.send(password)
  // return

  let sql = `SELECT * FROM e_member WHERE username = '${username}' AND password='${password}'`
  let res1 = await Query(sql)
  if (res1.result.length > 0) {
    // let data = {
    //   msg: '登录成功',
    //   status: 200,
    //   result:{
    //     //返回登录成功的标识，代表你当前登录这个用户
    //     mid:res1.result[0].mid,

    //   }
    // }
    let data = {
      username: res1.result[0].username,
      mid: res1.result[0].mid,
    }

    let token = getToken(data)
    // res.send(data);
    res.send({
      msg: "OK",
      status: 200,
      result: {
        token,
        mid: res1.result[0].mid
      }
    })
  } else {
    next({
      msg: '用户名或密码错误',
      status: 500
    })
  }
});


module.exports = router;